package gl.android.biyiqing;

import gl.API;
import gl.android.biyiqing.bean.Result;
import gl.common.BaseControl;
import gl.uitls.AndroidUtil;
import gl.uitls.MD5;
import gl.uitls.Tip;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class PassWordResetActivity extends BYQBaseActivity {

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
	public static final String EXTRA_personnumber = "com.example.android.authenticatordemo.extra.personnumber";
	public static final String EXTRA_TIME = "com.example.android.authenticatordemo.extra.TIME";
	public static final String EXTRA_CREATER = "com.example.android.authenticatordemo.extra.EXTRA_CREATER";
	public static final String EXTRA_TITLE = "com.example.android.authenticatordemo.extra.EXTRA_TITLE";
	public static final String EXTRA_CARDID = "com.example.android.authenticatordemo.extra.EXTRA_CARDID";
	public static final String EXTRA_TEL = "com.example.android.authenticatordemo.extra.EXTRA_TEL";

	public String IMEI = AndroidUtil.getIMEI();

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserChangePassWord mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String old = "";
	private String name = "";

	private String mPassword = "";

	// UI references.
	private EditText et_code;
	private EditText et_tel;
	private EditText et_password;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	private TextView code;
	private String codeId;
	private String tel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_pass_word_reset_byq);
		// cardid = getIntent().getStringExtra(EXTRA_EMAIL);
		name = getIntent().getStringExtra(EXTRA_CARDID);
		tel = getIntent().getStringExtra(EXTRA_TEL);
		// Set up the login form.
		// if (TextUtils.isEmpty(name)) {
		// Tip.show("账号不能是空");
		// return;
		// }
		// if (TextUtils.isEmpty(EXTRA_TEL)) {
		// Tip.show("电话号码不能是空");
		// return;
		// }
		et_code = (EditText) findViewById(R.id.oldpw);
		et_tel = (EditText) findViewById(R.id.tel);

		et_password = (EditText) findViewById(R.id.password);
		et_password
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});
		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});
		findViewById(R.id.showpw).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO showpw

					}

				});
		code = (TextView) findViewById(R.id.code);
		code.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				if (TextUtils.isEmpty(et_tel.getText())) {
					Tip.show("电话号码不能是空");
					return;
				}
				tel = et_tel.getText().toString();
				BaseControl.get(API.URL + "Checktel?tel=%s",
						new AjaxCallBack<String>() {
							@Override
							public void onStart() {
								super.onStart();

							}

							@Override
							public void onSuccess(String t) {
								super.onSuccess(t);
								mAuthTask = null;
								showProgress(false);
								JSONObject userList2;
								try {
									userList2 = new JSONObject(t);
									if (!TextUtils.isEmpty(userList2
											.optString("msg"))
											&& "2".equals(userList2
													.optString("msg"))) {
										code.setText("已发送");
										try {
											codeId = new JSONObject(userList2
													.optString("data").toString())
													.optString("id");
											name = new JSONObject(userList2
													.optString("data").toString())
													.optString("userid");
										} catch (JSONException e) {
											e.printStackTrace();
											onFailure(e, 0, "验证码ID获取失败");
										}
									}
									else if (!TextUtils.isEmpty(userList2
											.optString("msg"))
											&& "0".equals(userList2
													.optString("msg"))) {
										Tip.show("手机号码不存在");
									}
									else if (!TextUtils.isEmpty(userList2
											.optString("msg"))
											&& "1".equals(userList2
													.optString("msg"))) {
										Tip.show("验证码发送失败");
									}
								} catch (Exception e1) {
									onFailure(e1, 0,  e1.getMessage());
									e1.printStackTrace();
								}
								
							}

							@Override
							public void onFailure(Throwable t, int errorNo,
									String strMsg) {
								super.onFailure(t, errorNo, strMsg);
								mAuthTask = null;
								showProgress(false);
								et_tel.setError(t.getMessage() + "");
								et_tel.requestFocus();
							}
						}, tel);

			}
		});
		initTitleBar();
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		et_code.setError(null);

		// Store values at the time of the login attempt.
		old = et_code.getText().toString();
		mPassword = et_password.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			et_password.setError(getString(R.string.error_field_required));
			focusView = et_password;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(old)) {
			et_code.setError(getString(R.string.error_field_required));
			focusView = et_code;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		}
		else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserChangePassWord();
			mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		}
		else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserChangePassWord {

		public void execute(Void void1) {
			BaseControl.get(API.URL
					+ "Resetpassword?userid=%s&id=%s&code=%s&pwd=%s",
					new AjaxCallBack<String>() {
						@Override
						public void onSuccess(String t) {
							super.onSuccess(t);
							mAuthTask = null;
							showProgress(false);
							Result userList2 = new Gson().fromJson(t,
									new TypeToken<Result>() {
									}.getType());
							if (!TextUtils.isEmpty(userList2.getMsg())
									&& "2".equals(userList2.getMsg())) {
								Tip.showTipDialog(PassWordResetActivity.this,
										"修改成功,请重新登陆", "提示",
										new OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												finish();
												Intent intent = new Intent(
														PassWordResetActivity.this,
														LoginActivity.class);
												intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
												startActivity(intent);
											}
										});
							}
							else if (!TextUtils.isEmpty(userList2.getMsg())
									&& "0".equals(userList2.getMsg())) {
								Tip.show("验证码不正确 ");
							}
							else if (!TextUtils.isEmpty(userList2.getMsg())
									&& "1".equals(userList2.getMsg())) {
								Tip.show("验证码过期（180s）");
							}
						}

						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							super.onFailure(t, errorNo, strMsg);
							mAuthTask = null;
							showProgress(false);
							et_password.setError(t.getMessage() + "");
							et_password.requestFocus();
						}
					}, name, codeId, et_code.getText(), MD5.md5(mPassword));

		}
	}

	/* 定义一个倒计时的内部类 */
	class MyCount extends CountDownTimer {
		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			code.setEnabled(true);
			code.setText("获取验证码");
		}

		@Override
		public void onTick(long millisUntilFinished) {
			code.setEnabled(false);
			code.setText("重新获取(" + millisUntilFinished / 1000 + ")秒");
		}
	}
}
